from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import Q, Count
from django.utils import timezone
from django.http import JsonResponse, HttpResponse
from django.views.decorators.http import require_POST
from django.views.decorators.csrf import csrf_exempt
from .models import Post, Category, Tag, Comment
from .forms import PostForm, CommentForm, ReplyForm, CategoryForm, TagForm
import json


def home(request):
    """博客首页"""
    # 调试信息：检查数据库中的文章状态
    all_posts = Post.objects.all()
    published_posts = Post.objects.filter(status='published')
    valid_slug_posts = Post.objects.filter(slug__isnull=False).exclude(slug='')

    print(f"所有文章数量: {all_posts.count()}")
    print(f"已发布文章数量: {published_posts.count()}")
    print(f"有效slug文章数量: {valid_slug_posts.count()}")

    # 获取已发布文章
    posts = Post.objects.filter(
        status='published',
        publish_date__lte=timezone.now()
    ).order_by('-publish_date')

    featured_posts = posts.filter(featured_image__isnull=False)[:3]

    # 分页
    paginator = Paginator(posts, 6)
    page = request.GET.get('page')
    try:
        posts = paginator.page(page)
    except PageNotAnInteger:
        posts = paginator.page(1)
    except EmptyPage:
        posts = paginator.page(paginator.num_pages)

    # 获取分类和标签
    categories = Category.objects.annotate(post_count=Count('posts'))
    tags = Tag.objects.annotate(post_count=Count('posts')).order_by('-post_count')[:10]

    context = {
        'posts': posts,
        'featured_posts': featured_posts,
        'categories': categories,
        'tags': tags,
    }
    return render(request, 'blog/home.html', context)


def post_detail(request, year, month, day, slug):
    """文章详情页"""
    post = get_object_or_404(
        Post,
        slug=slug,
        publish_date__year=year,
        publish_date__month=month,
        publish_date__day=day,
        status='published',
        publish_date__lte=timezone.now()
    )

    # 增加浏览量
    post.views += 1
    post.save(update_fields=['views'])

    # 获取评论
    comments = post.comments.filter(active=True, parent=None).order_by('-created_at')

    # 评论表单
    comment_form = CommentForm()
    reply_form = ReplyForm()

    # 相关文章
    related_posts = Post.objects.filter(
        status='published',
        publish_date__lte=timezone.now(),
        category=post.category
    ).exclude(id=post.id)[:3]

    context = {
        'post': post,
        'comments': comments,
        'comment_form': comment_form,
        'reply_form': reply_form,
        'related_posts': related_posts,
    }
    return render(request, 'blog/post_detail.html', context)


@login_required
def post_create(request):
    """创建新文章"""
    if request.method == 'POST':
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user

            # 确保 slug 不为空
            if not post.slug:
                from django.utils.text import slugify
                post.slug = slugify(post.title)

            post.save()
            form.save_m2m()  # 保存多对多关系（标签）
            messages.success(request, '文章创建成功！')
            return redirect(post.get_absolute_url())
    else:
        form = PostForm()

    # 添加分类和标签表单
    category_form = CategoryForm()
    tag_form = TagForm()

    context = {
        'form': form,
        'title': '创建文章',
        'category_form': category_form,
        'tag_form': tag_form
    }
    return render(request, 'blog/post_form.html', context)


@login_required
def post_edit(request, pk):
    """编辑文章"""
    post = get_object_or_404(Post, pk=pk, author=request.user)

    if request.method == 'POST':
        form = PostForm(request.POST, request.FILES, instance=post)
        if form.is_valid():
            post = form.save(commit=False)

            # 确保 slug 不为空
            if not post.slug:
                from django.utils.text import slugify
                post.slug = slugify(post.title)

            post.save()
            form.save_m2m()  # 保存多对多关系（标签）
            messages.success(request, '文章更新成功！')
            return redirect(post.get_absolute_url())
    else:
        form = PostForm(instance=post)

    # 添加分类和标签表单
    category_form = CategoryForm()
    tag_form = TagForm()

    context = {
        'form': form,
        'title': '编辑文章',
        'post': post,
        'category_form': category_form,
        'tag_form': tag_form
    }
    return render(request, 'blog/post_form.html', context)


@login_required
def post_delete(request, pk):
    """删除文章"""
    post = get_object_or_404(Post, pk=pk, author=request.user)

    if request.method == 'POST':
        post.delete()
        messages.success(request, '文章已删除！')
        return redirect('home')

    context = {
        'post': post
    }
    return render(request, 'blog/post_confirm_delete.html', context)


@login_required
@require_POST
def add_comment(request, post_id):
    """添加评论"""
    post = get_object_or_404(Post, id=post_id)
    form = CommentForm(request.POST)

    if form.is_valid():
        comment = form.save(commit=False)
        comment.post = post
        comment.author = request.user
        comment.save()

        # 检查是否是 AJAX 请求
        if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
            return JsonResponse({
                'status': 'success',
                'comment_id': comment.id,
                'author': comment.author.username,
                'content': comment.content,
                'created_at': comment.created_at.strftime('%Y-%m-%d %H:%M')
            })

        messages.success(request, '评论已添加！')
        return redirect(post.get_absolute_url())

    # 检查是否是 AJAX 请求
    if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
        return JsonResponse({'status': 'error'})

    messages.error(request, '添加评论时出错！')
    return redirect(post.get_absolute_url())


@login_required
@require_POST
def add_reply(request, comment_id):
    """添加回复"""
    parent_comment = get_object_or_404(Comment, id=comment_id)
    form = ReplyForm(request.POST)

    if form.is_valid():
        reply = form.save(commit=False)
        reply.post = parent_comment.post
        reply.author = request.user
        reply.parent = parent_comment
        reply.save()

        # 检查是否是 AJAX 请求
        if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
            return JsonResponse({
                'status': 'success',
                'reply_id': reply.id,
                'author': reply.author.username,
                'content': reply.content,
                'created_at': reply.created_at.strftime('%Y-%m-%d %H:%M')
            })

        messages.success(request, '回复已添加！')
        return redirect(parent_comment.post.get_absolute_url())

    # 检查是否是 AJAX 请求
    if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
        return JsonResponse({'status': 'error'})

    messages.error(request, '添加回复时出错！')
    return redirect(parent_comment.post.get_absolute_url())


def category_detail(request, slug):
    """分类详情页"""
    category = get_object_or_404(Category, slug=slug)
    posts = Post.objects.filter(
        category=category,
        status='published',
        publish_date__lte=timezone.now(),
        slug__isnull=False
    ).exclude(slug='').order_by('-publish_date')

    # 分页
    paginator = Paginator(posts, 6)
    page = request.GET.get('page')
    try:
        posts = paginator.page(page)
    except PageNotAnInteger:
        posts = paginator.page(1)
    except EmptyPage:
        posts = paginator.page(paginator.num_pages)

    context = {
        'category': category,
        'posts': posts,
    }
    return render(request, 'blog/category_detail.html', context)


def tag_detail(request, slug):
    """标签详情页"""
    tag = get_object_or_404(Tag, slug=slug)
    posts = Post.objects.filter(
        tags=tag,
        status='published',
        publish_date__lte=timezone.now(),
        slug__isnull=False
    ).exclude(slug='').order_by('-publish_date')

    # 分页
    paginator = Paginator(posts, 6)
    page = request.GET.get('page')
    try:
        posts = paginator.page(page)
    except PageNotAnInteger:
        posts = paginator.page(1)
    except EmptyPage:
        posts = paginator.page(paginator.num_pages)

    context = {
        'tag': tag,
        'posts': posts,
    }
    return render(request, 'blog/tag_detail.html', context)


def search(request):
    """搜索功能"""
    query = request.GET.get('q', '')

    if query:
        posts = Post.objects.filter(
            Q(title__icontains=query) | Q(content__icontains=query),
            status='published',
            publish_date__lte=timezone.now(),
            slug__isnull=False
        ).exclude(slug='').order_by('-publish_date')
    else:
        posts = Post.objects.none()

    # 分页
    paginator = Paginator(posts, 6)
    page = request.GET.get('page')
    try:
        posts = paginator.page(page)
    except PageNotAnInteger:
        posts = paginator.page(1)
    except EmptyPage:
        posts = paginator.page(paginator.num_pages)

    context = {
        'query': query,
        'posts': posts,
    }
    return render(request, 'blog/search_results.html', context)


@login_required
@require_POST
def create_category(request):
    """创建新分类"""
    form = CategoryForm(request.POST)
    if form.is_valid():
        category = form.save()
        # 返回JSON响应，用于AJAX请求
        if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
            return JsonResponse({
                'status': 'success',
                'id': category.id,
                'name': category.name,
                'slug': category.slug
            })
        messages.success(request, f'分类 "{category.name}" 创建成功！')
        return redirect('post_create')
    else:
        # 返回错误信息
        if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
            return JsonResponse({
                'status': 'error',
                'errors': form.errors
            }, status=400)
        messages.error(request, '创建分类失败，请检查输入！')
        return redirect('post_create')

@login_required
@require_POST
def create_tag(request):
    """创建新标签"""
    form = TagForm(request.POST)
    if form.is_valid():
        tag = form.save()
        # 返回JSON响应，用于AJAX请求
        if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
            return JsonResponse({
                'status': 'success',
                'id': tag.id,
                'name': tag.name,
                'slug': tag.slug
            })
        messages.success(request, f'标签 "{tag.name}" 创建成功！')
        return redirect('post_create')
    else:
        # 返回错误信息
        if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
            return JsonResponse({
                'status': 'error',
                'errors': form.errors
            }, status=400)
        messages.error(request, '创建标签失败，请检查输入！')
        return redirect('post_create')

@login_required
def manage_taxonomies(request):
    """管理分类和标签页面"""
    categories = Category.objects.annotate(post_count=Count('posts')).order_by('name')
    tags = Tag.objects.annotate(post_count=Count('posts')).order_by('name')

    category_form = CategoryForm()
    tag_form = TagForm()

    context = {
        'categories': categories,
        'tags': tags,
        'category_form': category_form,
        'tag_form': tag_form
    }
    return render(request, 'blog/manage_taxonomies.html', context)
